package com.inspur.edp.formserver.vmmanager;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspur.edp.formserver.viewmodel.Context;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.formserver.viewmodel.VoThreadLoacl;
import com.inspur.edp.formserver.viewmodel.exception.ViewModelException;
import com.inspur.edp.formserver.vmmanager.exception.VoManagerErrorCodes;
import com.inspur.edp.lcm.metadata.api.IMetadataContent;
import com.inspur.edp.lcm.metadata.spi.MetadataContentSerializer;

import java.io.IOException;

/**
 * @author shksatrt
 * @DATE 2019/7/29 - 10:12
 */
public class ContentSerializer implements MetadataContentSerializer {

    @Override
    public JsonNode Serialize(IMetadataContent iMetadataContent) {
        Context context = new Context();
        context.setfull(false);
        VoThreadLoacl.set(context);
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
        try {
            String json = mapper.writeValueAsString(iMetadataContent);
            JsonNode jsonNode = mapper.readTree(json);
            return jsonNode;
        } catch (JsonProcessingException e) {
            throw new ViewModelException(e);
        } catch (IOException e) {
            throw new ViewModelException(e);
        } catch (RuntimeException e) {
            throw new ViewModelException(e);
        } finally {
            VoThreadLoacl.unset();
        }
    }

    @Override
    public IMetadataContent DeSerialize(JsonNode jsonNode) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            GspViewModel vm = mapper.readValue(handleJsonString(jsonNode.toString()), GspViewModel.class);
            return vm;
        } catch (IOException e) {
            throw new ViewModelException(VoManagerErrorCodes.GSP_VIEWOBJECT_MANAGER_0097, e);
        }
    }

    private static String handleJsonString(String contentJson) {
        if (contentJson.startsWith("\"")) {
            contentJson = contentJson.replace("\\\"", "\"");
            while (contentJson.startsWith("\"")) {
                contentJson = contentJson.substring(1, contentJson.length() - 1);
            }
        }
        return contentJson;
    }
}
